package com.ea.demo.autogenapi.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.ea.demo.autogenapi.base.vo.BaseResponseVo;
import com.ea.demo.autogenapi.base.vo.DefaultResponseVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class ExceptionResolver implements HandlerExceptionResolver {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        logger.error("系统全局异常",e);

        int code = BaseResponseVo.SYSYTEM_EXCEPTION;
        String message = "系统异常";

        if(e instanceof IllegalArgumentException) {
            code = BaseResponseVo.INVALID_PARAM;
            message = e.getMessage();
        }
        FastJsonJsonView fastJsonJsonView = new FastJsonJsonView();
        ModelAndView modelAndView = new ModelAndView();
        fastJsonJsonView.setAttributesMap(JSON.parseObject(JSON.toJSONString(DefaultResponseVo.fail(code,message)), Map.class));
        modelAndView.setView(fastJsonJsonView);
        return modelAndView;
    }
}
